﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GameSchool.Models;
using GameSchool.Models.AccountModels;

namespace GameSchool.DAL
{
    public class CourseRepository : ICourseRepository, IDisposable
    {
        // Nánari upplýsingar um hvernig Repository patternið virkar er á:
        // http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

        /// <summary>
        /// Meðlimabreyta sem er gagnagrunnstengingin
        /// </summary>
        private gsEntities m_db;

        /// <summary>
        /// Class Initializer sem tekur við gagnagrunnstengingu sem skal nota
        /// </summary>
        /// <param name="db"></param>
        public CourseRepository(gsEntities db)
        {
            this.m_db = db;
        }

        /// <summary>
        /// Skilar lista yfir öll prófin
        /// </summary>
        /// <returns></returns>
        public List<Course> GetCourses()
        {
            return m_db.Course.ToList();
        }

        public List<CourseRules> GetCourseRules(int courseId)
        {
            return m_db.CourseRules.OrderBy(i => i.SortOrder).ToList();
        }

        public List<CourseStudents> GetCourseStudents(int courseId)
        {
            return m_db.CourseStudents
                .Where(i => i.CourseID == courseId)
                .ToList();
        }

        /// <summary>
        /// Skilar lista yfir öll námskeið, formað fyrir Administrator
        /// </summary>
        /// <returns></returns>
        public List<vCoursesAdmin> GetCoursesAdmin()
        {
            return m_db.vCoursesAdmin
                .OrderBy(o => o.SemesterName)
                .ThenBy(o => o.Name)
                .ToList();
        }

        /// <summary>
        /// Skilar lista yfir öll námskeið, formað fyrir Nemanda
        /// </summary>
        /// <param name="studentUserId"></param>
        /// <returns></returns>
        public List<vCoursesStudent> GetCoursesStudent(Guid studentUserId)
        {
            return m_db.vCoursesStudent
                .Where(w => w.StudentUserID == studentUserId)
                .OrderBy(o => o.SemesterName)
                .ThenBy(o => o.Name)
                .ToList();
        }

        /// <summary>
        /// Skilar lista yfir öll námskeið, formað fyrir Kennara
        /// </summary>
        /// <param name="teacherUserId"></param>
        /// <returns></returns>
        public List<vCoursesTeacher> GetCoursesTeacher(Guid teacherUserId)
        {
            return m_db.vCoursesTeacher
                .Where(w => w.TeacherUserId == teacherUserId)
                .OrderBy(o => o.SemesterName)
                .ThenBy(o => o.Name)
                .ToList();
        }

        /// <summary>
        /// Sækir eitt próf eftir ID
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public Course GetCourseById(int courseId)
        {
            return m_db.Course.SingleOrDefault(e => e.CourseID == courseId);
        }

        public List<vSemesters> GetSemesters()
        {
            return m_db.vSemesters
                .OrderBy(o => o.Year)
                .ThenBy(o => o.SemesterOfYear)
                .ToList();
        }

        List<string> ICourseRepository.GetStudents()
        {
            var ret = new List<string>();

            foreach (var s in m_db.vUsers.Where(w => w.UserType == "Nemandi"))
            {
                ret.Add(string.Format("{0} ({1})", AccountProfile.GetProfileByUserName(s.UserName).FullName, s.UserName));
            }

            return ret.OrderByDescending(i => i).ToList();
        }

        public Dictionary<Guid, string> GetTeachers()
        {
            var teachers = m_db.vUsers.Where(w => w.UserType == "Kennari");
            var ret = new Dictionary<Guid, string>();

            foreach (var u in teachers)
            {
                ret.Add(u.UserId, AccountProfile.GetProfileByUserName(u.UserName).FullName);
            }

            return ret;
        }

        public CourseStudents AddStudentToCourse(int courseId, Guid studentUserId, bool isInstructor)
        {
            if (!m_db.CourseStudents.Any(i => i.CourseID == courseId && i.StudentUserID == studentUserId))
            {
                var studentToAdd = new CourseStudents()
                                       {
                                           CourseID = courseId,
                                           StudentUserID = studentUserId,
                                           IsInstructor = isInstructor
                                       };

                m_db.CourseStudents.AddObject(studentToAdd);

                return studentToAdd;
            }
            else
            {
                return null;
            }
        }

        public void RemoveStudentFromCourse(int courseId, Guid studentUserId)
        {
            var courseStudent = m_db.CourseStudents.SingleOrDefault(i => i.CourseID == courseId && i.StudentUserID == studentUserId);

            if (courseStudent != null)
            {
                m_db.CourseStudents.DeleteObject(courseStudent);
            }
        }

        public void UpdateStudentInstructorStatus(int courseId, Guid studentUserId, bool isInstructor)
        {
            var courseStudent = m_db.CourseStudents.Single(i => i.CourseID == courseId && i.StudentUserID == studentUserId);
            courseStudent.IsInstructor = isInstructor;
        }

        /// <summary>
        /// Bætir við námskeiði í gagnagrunninn. ATH: Vistar ekki sjálfkrafa
        /// </summary>
        /// <param name="course"></param>
        public void InsertCourse(Course course)
        {
            m_db.Course.AddObject(course);
        }

        /// <summary>
        /// Uppfærir námskeið í gagnagrunninum. ATH: Vistar ekki sjálfkrafa
        /// </summary>
        /// <param name="course"> </param>
        public void UpdateCourse(Course course)
        {
            m_db.Course.Attach(course);
        }

        /// <summary>
        /// Vistar breytingar sem gerðar voru í sessioninu
        /// </summary>
        public void Save()
        {
            m_db.SaveChanges();
        }

        #region Disposerinn fyrir using() statement - Alltaf eins
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    m_db.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}